<?php

namespace App\Listeners;

use App\Events\ReplaceOrInsertLatestMessage;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Http\Resources\LatestMessageResource;
use App\Models\Group;


//通知群聊和朋友圈更新
class NotificationReplaceOrInsertLatestMessage
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ReplaceOrInsertLatestMessage  $event
     * @return void
     */
    public function handle(ReplaceOrInsertLatestMessage $event)
    {
        $latestMessage = $event->latestMessage;

        $group = Group::find($latestMessage->group_id);
        
        if($group){
            if($group->extra_type==2){//朋友圈群聊，顺便通知朋友圈更新
                event(new \App\Events\ReplaceOrInsertPostLatestMessage($latestMessage));
            }else{
                \Log::info('ReplaceOrInsertLatestMessage:',[
                    'code' => 0,
                    'msg' =>'非朋友圈',
                    'data' =>[
                        'event' => 'ReplaceOrInsertLatestMessage',
                        'latest_message' => $latestMessage->id,
                    ],
                ]);
            }
        }else{
            \Log::info('ReplaceOrInsertLatestMessage:',[
                'code' => 1,
                'msg' =>'找不到群组',
                'data' =>[
                    'event' => 'ReplaceOrInsertLatestMessage'
                ],
            ]);
        }

        
        //通知群
        app('gateway')->sendToGroup($latestMessage->group_id,[
            'type'=>'replace_or_insert_latest_message',
            'content' => new LatestMessageResource($latestMessage)
        ],null,'im_replace_or_insert_latest_message');

        //（加入了朋友圈的群聊的用户会被通知两次） （可通过，获取群聊的和朋友圈用户的差集去循环推送
    }
}
